import tkinter as tk
from tkinter import Frame

class WinLogin(tk.Tk):
    def __init__(self):
        super(WinLogin,self).__init__()
        self.window_init()
        self.create_widgets()

    def window_init(self):
        self.title('登录')
        self.resizable(False,False)

        #在屏幕居中显示
        window_width = 260
        window_height = 90
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()
        pos_x = (screen_width - window_width)/2
        pos_y = (screen_height - window_height)/2
        self.geometry('%dx%d+%d+%d' % (window_width,window_height,pos_x,pos_y))

    def create_widgets(self):
        #用户名输入
        self.lab_user = tk.Label(self,text='用户名：')
        self.lab_user.grid(row=0,column=0,sticky=tk.W+tk.E,padx=10,pady=5)
        self.entry_user = tk.Entry(self,name='entry_user',width=25)
        self.entry_user.grid(row=0,column=1,sticky=tk.W+tk.E)
        #密码输入
        self.lab_pwd = tk.Label(self,text='密码：')
        self.lab_pwd.grid(row=1,column=0,sticky=tk.W+tk.E)
        self.entry_pwd = tk.Entry(self,name='entry_pwd',show='*')
        self.entry_pwd.grid(row=1,column=1,sticky=tk.W+tk.E)
        #确认按钮、注册按钮
        self.button_frame = Frame(self,name='button_frame')
        self.button_login = tk.Button(self.button_frame,name='button_login',text="登录",width=5)
        self.button_login.pack(side='left',padx=20)
        self.button_enrol = tk.Button(self.button_frame,name='button_enrol',text="退出",width=5)
        self.button_enrol.pack(side='right')
        self.button_frame.grid(row=2,columnspan=2)

    def get_username(self):
        return self.children['entry_user'].get()
    def get_pwd(self):
        return self.children['entry_pwd'].get()

    #外界传递函数，控制按钮按下事件
    def on_button_login_click(self,command):
        button_login = self.children['button_frame'].children['button_login']
        button_login['command'] = command
    def on_button_enrol_click(self,command):
        button_enrol = self.children['button_frame'].children['button_enrol']
        button_enrol['command'] = command

    def on_window_closed(self,command):
        self.protocol('WM_DELETE_WINDOW',command)

def testGet():
    print("testGet()...")
    print(app.get_username())
    print(app.get_pwd())

if __name__ == '__main__':
    app = WinLogin()
    app.on_button_login_click(testGet)
    app.mainloop()

